package com.xc.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xc.dao.SiteSettingMapper;
import com.xc.pojo.SiteSetting;
import com.xc.service.ISiteSettingService;
import com.xc.stock.constant.ErrorTipEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

/**
 * 转换Response错误提示工具
 *
 * @author jnerh
 * @since 2023-07-17 10:26
 */
@Slf4j
@Component
public class TransferErrorTipUtil {

    @Resource
    private ISiteSettingService siteSettingService;

    /**
     * 转换错误提示
     *
     * @param httpServletRequest request
     * @param httpServletResponse response
     */
    public void transferErrorTip(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        InputStream contentInputStream = ((ContentCachingResponseWrapper) httpServletResponse).getContentInputStream();
        String s = inputStream2String_Scanner(contentInputStream);
        JSONObject jsonObject = JSON.parseObject(s, Feature.OrderedField);
        String msg = jsonObject.getString("msg");;
        if (msg == null) {
            msg = jsonObject.getString("data");
        }

        if (msg == null || !msg.startsWith("tips.msg.")) {
            return;
        }

        String remark = ErrorTipEnum.remark(msg);
        if (remark.equals("未知错误")) {
            return;
        }

        if (jsonObject.getString("msg") != null) {
            jsonObject.put("msg", replaceVar(remark));
        }
        if (jsonObject.getString("data") != null
                && jsonObject.getString("data").startsWith("tips.msg.")) {
            jsonObject.put("data", replaceVar(remark));
        }

        try {
            httpServletResponse.resetBuffer();
            httpServletResponse.getWriter().write(JSON.toJSONString(jsonObject, SerializerFeature.WRITE_MAP_NULL_FEATURES));
            httpServletResponse.getWriter().flush();
        } catch (IOException ioException) {
            log.info("Response错误提示转换失败, " + ioException.getLocalizedMessage());
        } finally {
            try {
                httpServletResponse.getWriter().close();
            } catch (Exception e) {
                log.info("Response关闭writer失败, " + e.getLocalizedMessage());
            }
        }
    }

    private String replaceVar(String remark) {
        SiteSetting siteSetting = siteSettingService.getSiteSetting();
        if (remark.contains("{buyMinAmt}")) {
            // 替换变量
            Integer buyMinAmt = siteSetting.getBuyMinAmt();
            remark = remark.replace("{buyMinAmt}", buyMinAmt + "");
        }

        return remark;
    }

    /**
     * 将输入流转为字符串
     *
     * @param is 输入流
     * @return 字符串
     */
    public static String inputStream2String_Scanner(InputStream is){
        StringBuilder  stringBuilder = new StringBuilder();
        Scanner scanner = new Scanner(is);
        while(scanner.hasNext()){
            String text = scanner.useDelimiter("\\A").next();
            stringBuilder.append(text);
        }

        scanner.close();
        return stringBuilder.toString();
    }
}
